package net.wangds.data;

import net.wangds.common.base.funcs.Functions;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * 树.
 * @param <T> 子节点类型.
 */
public interface Tree<I, T extends Tree<I, T>> {

    /**
     * 将节点列表整理成森林.
     * @param trees 节点列表.
     * @param <T> 节点类型.
     * @return 森林.
     */
    static <T extends Tree> List<T> trees(List<T> trees){
        return Functions.toTrees(trees, FUNC_ID_GETTER, FUNC_PARENT_ID_GETTER, FUNCTION_COMBINE);
    }

    /**
     * 获得当前节点id的方法.
     */
    Function<Tree, Object> FUNC_ID_GETTER = Tree::getId;
    /**
     * 获得父节点id的方法.
     */
    Function<Tree, Object> FUNC_PARENT_ID_GETTER = Tree::getParentId;
    /**
     * 把子节点添加到父节点的方法.
     */
    BiFunction<Tree, Tree, Tree> FUNCTION_COMBINE = (p, c)->{
        List cs = p.getChildren();
        if(cs==null){
            cs = new ArrayList<>();
            p.setChildren(cs);
        }
        cs.add(c);
        return p;
    };

    I getId();

    I getParentId();

    List<T> getChildren();

    void setChildren(List<T> children);

    String getBranchPath();

    void setBranchPath(String branchPath);

}
